﻿namespace TheCodeWerks.Advertising
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Net;
	using System.Reflection;
	using System.Runtime.Serialization;

	[DataContract]
	public partial class AdvertisingConfiguration
	{
		public const string VersionHttpHeader = "X-Configuration-Version";

		private static readonly Version version;
	}

	public partial class AdvertisingConfiguration
	{
		[DataMember]
		public List<string> DefaultKeywords = new List<string>();		

		[DataMember]
		public Dictionary<int, AdPlacement> Placements = new Dictionary<int, AdPlacement>();

		[DataMember]
		public Dictionary<AdProvider, AdProviderSettings> Providers = new Dictionary<AdProvider, AdProviderSettings>();

		[DataMember]
		public bool TestMode;

		[DataMember]
		public UserInformation User = new UserInformation();
	}

	// Static Methods
	public partial class AdvertisingConfiguration
	{
		static AdvertisingConfiguration()
		{
			var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
			version = new Version(((AssemblyFileVersionAttribute)attributes[0]).Version);
		}

		public static void Get(Uri uri, Action<HttpWebRequest> onrequest, Action<AdvertisingConfiguration> configLoaded)
		{
			if (configLoaded == null) throw new ArgumentNullException("configLoaded");

			var request = HttpWebRequest.CreateHttp(uri);

			if (onrequest != null) onrequest(request);

			request.Headers[VersionHttpHeader] = version.ToString();

			request.BeginGetResponse
			(
				result =>
				{
					try
					{
						var response = (HttpWebResponse)request.EndGetResponse(result);

						if (request.HaveResponse)
						{
							if (response.StatusCode == HttpStatusCode.OK)
							{
								var serializer = new DataContractSerializer(typeof(AdvertisingConfiguration));
								var config = (AdvertisingConfiguration)serializer.ReadObject(response.GetResponseStream());

								configLoaded(config);
							}
						}
					}
					catch { }
				},
				null
			);
		}
	}

	// Instance Methods
	public partial class AdvertisingConfiguration
	{
		public override string ToString()
		{
			using (var stream = new MemoryStream())
			{
				var serializer = new DataContractSerializer(typeof(AdvertisingConfiguration));

				serializer.WriteObject(stream, this);
				stream.Position = 0;

				return (new StreamReader(stream)).ReadToEnd();
			}
		}
	}
}
